<?php

require_once('functions/pageLoad.php');
require_once("classes/class.phpmailer.php");

if($_SERVER['REQUEST_METHOD'] == 'POST' && strlen($_POST['first_name']) == 0 && isset($_POST['home_job_post'])){

// validate

$email_regex = "/^[^@]+@([-\w]+\.)+[A-Za-z]{2,4}$/i";
$postcode_regex = "/^([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw])\ {0,1}[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}|([Gg][Ii][Rr]\ 0[Aa][Aa])|([Ss][Aa][Nn]\ {0,1}[Tt][Aa]1)|([Bb][Ff][Pp][Oo]\ {0,1}([Cc]\/[Oo]\ )?[0-9]{1,4})|(([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[BFSbfs][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]|[Tt][Kk][Cc][Aa])\ {0,1}1[Zz][Zz]))$/i";

// check email

	$sql = "SELECT id FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rows=mysql_num_rows($query);

$fail.= (strlen($_POST['title']) == 0) ? '<li>Job title was not entered</li>' : '';
$fail.= (strlen($_POST['description']) == 0) ? '<li>Requirements were not entered</li>' : '';
$fail.= (strlen($_POST['trade']) == 0) ? '<li>Trade was not entered</li>' : '';

//Change By Vyas Ishan 14 May 2013 Task1
#$fail.= (strlen($_POST['firstname']) == 0 || strlen($_POST['surname']) == 0) ? '<li>Name was not entered</li>' : '';
$fail.= (strlen($_POST['firstname']) == 0) ? '<li>Name was not entered</li>' : '';

$fail.= (strlen($_POST['telephone']) == 0 && strlen($_POST['mobile']) == 0) ? '<li>At least one telephone number must be entered</li>' : '';
$fail.= (strlen($_POST['telephone']) > 0 && !ctype_digit(str_replace(" ", "", $_POST['telephone']))) ? '<li>Invalid telephone number entered, please use numbers only</li>' : '';
$fail.= (strlen($_POST['mobile']) > 0 && !ctype_digit(str_replace(" ", "", $_POST['mobile']))) ? '<li>Invalid telephone number entered, please use numbers only</li>' : '';
$fail.= (preg_match($email_regex, $_POST['email']) == 0) ? '<li>Invalid email address entered</li>' : '';
$fail.= ($rows > 0) ? '<li>An account already exists with that email address, please <a href="/sign-in">login</a> to post your job</li>' : '';
$fail.= (strlen($_POST['line_1']) == 0) ? '<li>Address was not entered</li>' : '';
$fail.= (strlen($_POST['city']) == 0) ? '<li>City was not entered</li>' : '';

//Change By Vyas Ishan 16 May 2013 Task1
#$fail.= (preg_match($postcode_regex, str_replace(" ", "", $_POST['postcode'])) == 0) ? '<li>Invalid postcode entered</li>' : '';
$fail.= (strlen(  trim($_POST['postcode'])  ) == 0)? '<li>Invalid postcode entered</li>' : '';

$fail.= ($_POST['terms'] != '1') ? '<li>You must agree to the terms of use</li>' : '';

	if(strlen($fail) > 0){

	// PHAIL

	$results = '<h1>Registration error!</h1><p>Please correct the following errors;</p><ul>'.$fail.'</ul>';

	}

	else
	{

	// FINE - INSERT, SEND EMAIL AND REDIRECT

	$password = createRandomPassword();

		$mail = new PHPMailer();
		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->Host = "localhost"; // SMTP server
		$mail->From = $settings['no_reply_email'];
		$mail->FromName = "I Want A Tradesman";

		$mail->AddAddress($_POST['email']);

		$mail->Subject = "Welcome to I Want A Tradesman!";
		$mail->Body = "Dear ".$_POST['firstname']." ".$_POST['surname']."\r\n\r\nWelcome to I Want A Tradesman, your job has been posted and you should start receiving quotes soon. If you would like to make any changes to your job or would like to add additional information. Please login to your new account using the details below.\r\n\r\nEmail: ".$_POST['email']."\r\nPassword: ".$password."\r\n\r\nYou can also sign in to:\r\n\r\n-	Post more jobs\r\n-	View quotes\r\n-	Leave feedback\r\n\r\nIf you have any enquiries, please do not hesitate to e-mail us on ".$settings['site_email'].".\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

		$mail->Send();

		// insert user, email has sent and does not already exist in db
		
		//Change By Vyas Ishan 14 May 2013 Task 1
		$surName = '';
		if (array_key_exists('surname',$_POST)) {
			$surName = mysql_real_escape_string(stripslashes($_POST['surname']));
		}			
			
		$sql="INSERT INTO users (email, firstname, surname, telephone, mobile, newsletter, member_since, last_login) VALUES ('".mysql_real_escape_string(stripslashes($_POST['email']))."', '".mysql_real_escape_string(stripslashes($_POST['firstname']))."', '".$surName."', '".mysql_real_escape_string(str_replace(" ", "", $_POST['telephone']))."', '".mysql_real_escape_string(str_replace(" ", "", $_POST['mobile']))."', '".mysql_real_escape_string($_POST['newsletter'])."', NOW(), NOW())";
		$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
		$user_id = mysql_insert_id();

		// free sms

		$sql="INSERT INTO SMS (user_id, sms_remaining) VALUES ('".$user_id."', '1000')";
		$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());

		// encrypt password

		$encrypt1 = base64_encode($password.'_'.$encryption_salt);
		$encrypt2 = md5($encrypt1.'_'.$_POST['email'].'_'.$encryption_salt);

		// add address

		// google map

		$address = $_POST['line_1'].",".$_POST['line_2'].",".$_POST['line_3'].",".$_POST['postcode'];
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&oe=utf8&sensor=false&key=".$settings['google_api_key']);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
		$outputArr = explode(",",$output);

		$sql="INSERT INTO addresses (user_id, area_id, line_1, line_2, line_3, postcode, longitude, latitude) VALUES ('".$user_id."', '".mysql_real_escape_string($_POST['city'])."', '".mysql_real_escape_string(stripslashes($_POST['line_1']))."', '".mysql_real_escape_string(stripslashes($_POST['line_2']))."', '".mysql_real_escape_string(stripslashes($_POST['line_3']))."', '".mysql_real_escape_string(strtoupper($_POST['postcode']))."', '".$outputArr[3]."', '".$outputArr[2]."')";
		$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
		$address_id = mysql_insert_id();

		// update user

		$userUpdate="UPDATE users SET address_id = '".$address_id."', password = '".$encrypt2."' WHERE id = '".$user_id."'";
		$userResult=mysql_query( $userUpdate ) or die ("Error in query: $userUpdate . " . mysql_error());

		$_SESSION['user'] = $user_id.'_'.$_SERVER['REMOTE_ADDR'];
		
	// INSERT JOB

		$sql = "INSERT INTO jobs (user_id, address_id, area_id, trade_id, date_added, title, description, materials, status) VALUES ('".$user_id."','".$address_id."','".mysql_real_escape_string($_POST['city'])."','".mysql_real_escape_string($_POST['trade'])."', NOW(),'".mysql_real_escape_string(stripslashes($_POST['title']))."','".mysql_real_escape_string(stripslashes($_POST['description']))."', '".mysql_real_escape_string($_POST['materials'])."', 'Pending')";
		$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
		$job_id = mysql_insert_id();
		
			$mail1 = new PHPMailer();
			$mail1->IsSMTP(); // telling the class to use SMTP
			$mail1->Host = "localhost"; // SMTP server
			$mail1->From = $settings['no_reply_email'];
			$mail1->FromName = "I Want A Tradesman";

			$mail1->AddAddress($settings['site_email']);

			$mail1->Subject = "New job awaiting moderation";
			$mail1->Body = "http://www.iwantatradesman.co.uk/admin/";

			$mail1->Send();

		header("Location: /my-account");

	}

}

$page_title='Find Local Tradesmen UK Online Tradesmen Quotes Best Tradesmen Directory';
$page_description='Local Tradesmen- I want tradesmen is local tradesmen directory in UK for best quote for tradesmen, local electrician and local plumber in UK';
$page_keywords='Local tradesmen, tradesmen directory, UK tradesmen, plumber in UK, electrican in UK, free online quotes in UK, find tradesmen in UK';

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

		<h1 id="home_header">Free online quotes from local tradesmen!</h1>
		
		<img src="images/process.jpg" alt="" id="process">

		<section>
		
			<h1>Post your job</h1>
			
			<p>Post a job to our system for free and start receiving quotes straight away! You will receive your login details by email, enabling you to keep track and manage your job. You will be able to add more information later and upload pictures to improve your job listing.</p>
			
			<?php echo $results; ?>
			
			<form method="post" id="post_job_form">
			
			<input type="text" name="first_name" style="display: none;">
			<input type="hidden" name="home_job_post" value="true">
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="title">Job title</label></div>
			<div class="rowRight"><input type="text" name="title" id="title" placeholder="Enter a short description of your requirements." value="<?php echo $_POST['title']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="description">Requirements</label></div>
			<div class="rowRight"><textarea name="description" id="description" placeholder="Enter a detailed description of your requirements, include all information that might be useful to our tradesmen."><?php echo $_POST['description']; ?></textarea></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="trade">Trade</label></div>
			<div class="rowRight"><select name="trade" id="trade"<?php echo (isset($_POST['trade'])) ? ' style="color: #000000; font-style: normal;"' : '' ; ?>>
			<option value="" disabled <?php echo (!isset($_POST['trade'])) ? 'selected ' : '' ; ?>class="disabled">Select the type of trade you require.</option>
			<?php
			
			$sql = "SELECT id, trade FROM trades ORDER BY trade";
			$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

			while($rs=mysql_fetch_assoc($query)){
			
			$selected = ($_POST['trade'] == $rs['id']) ? ' selected' : '' ;
			
			echo '<option value="'.$rs['id'].'"'.$selected.'>'.htmlspecialchars($rs['trade']).'</option>'."\r\n";
			
			}
			
			?>
			</select></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="materials">Materials</label></div>
			<div class="rowRight"><input type="checkbox" name="materials" id="materials" value="1"<?php echo ($_POST['materials'] == '1') ? ' checked' : '' ; ?>> <label for="materials">I will supply the materials needed to complete the job.</label></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="email">Email</label></div>
			<div class="rowRight"><input type="text" name="email" id="email" placeholder="Enter your email address to receive your login details. Your details are safe." value="<?php echo $_POST['email']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="telephone">Telephone</label></div>
			<div class="rowRight"><input type="text" name="telephone" id="telephone" placeholder="Enter at least one contact telephone number for tradesmen to contact you on." value="<?php echo $_POST['telephone']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="mobile">Mobile</label></div>
			<div class="rowRight"><input type="text" name="mobile" id="mobile" value="<?php echo $_POST['mobile']; ?>"></div>
			</div>

			<div class="rowWrapper">
			<div class="rowLeft"><label for="firstname">Your name</label></div>
			<div class="rowRight">
				<input type="text" name="firstname" id="firstname" style="width: 210px;" placeholder="Your first name." value="<?php echo $_POST['firstname']; ?>"> 
				<?php /* //Change By Vyas Ishan 14 May 2013 Task 1?>
				<input type="text" name="surname" id="surname" style="width: 210px; margin-left: 6px;" placeholder="Your last name." value="<?php echo $_POST['surname']; ?>">
				<?php */?>
			</div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="address">Address</label></div>
			<div class="rowRight"><input type="text" name="line_1" id="line_1" placeholder="Enter your address so that we can locate tradesmen that are local to your area." value="<?php echo $_POST['line_1']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft">&nbsp;</div>
			<div class="rowRight"><input type="text" name="line_2" value="<?php echo $_POST['line_2']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft">&nbsp;</div>
			<div class="rowRight"><input type="text" name="line_3" value="<?php echo $_POST['line_3']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="city">Town</label></div>
			<div class="rowRight"><select name="city" id="city"<?php echo (isset($_POST['city'])) ? ' style="color: #000000; font-style: normal;"' : '' ; ?>>
			<option value="" disabled <?php echo (!isset($_POST['trade'])) ? 'selected ' : '' ; ?>class="disabled">Select your town/city.</option>
			<?php
			
			$sql = "SELECT id, area FROM areas ORDER BY area";
			$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

			while($rs=mysql_fetch_assoc($query)){
			
			$selected = ($_POST['city'] == $rs['id']) ? ' selected' : '' ;
			
			echo '<option value="'.$rs['id'].'"'.$selected.'>'.htmlspecialchars($rs['area']).'</option>'."\r\n";
			
			}
			
			?>
			</select></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft"><label for="postcode">Postcode</label></div>
			<div class="rowRight"><input type="text" name="postcode" id="postcode" value="<?php echo $_POST['postcode']; ?>"></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft">&nbsp;</div>
			<div class="rowRight"><input type="checkbox" name="newsletter" id="newsletter" value="1"<?php echo ($_POST['newsletter'] == '1') ? ' checked' : '' ; ?>> <label for="newsletter">Yes, I would like to receive the weekly newsletter from I Want A Tradesman.</label></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft">&nbsp;</div>
			<div class="rowRight"><input type="checkbox" name="terms" id="terms" value="1"<?php echo ($_POST['terms'] == '1') ? ' checked' : '' ; ?>> <label for="terms">I confirm I have read and agreed to the <a href="#">terms of use</a> and <a href="#">privacy policy</a>.</label></div>
			</div>
			
			<div class="rowWrapper">
			<div class="rowLeft">&nbsp;</div>
			<div class="rowRight">
			<input type="image" src="images/post_my_job_button.png" alt="Post my job">
			</div>
			</div>
			
			</form>
		
		</section>

<?php 

include('includes/rightColumn.php');
include('includes/footer.php');

?>